package com.shqcjd.preinstallglass.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.google.gson.Gson;
import com.open.androidtvwidget.bridge.EffectNoDrawBridge;
import com.open.androidtvwidget.bridge.OpenEffectBridge;
import com.open.androidtvwidget.view.FrameMainLayout;
import com.open.androidtvwidget.view.MainUpView;
import com.orhanobut.logger.Logger;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.shqcjd.preinstallglass.R;
import com.shqcjd.preinstallglass.api.ApiService;
import com.shqcjd.preinstallglass.app.AppConstant;
import com.shqcjd.preinstallglass.app.MyApp;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxObserver;
import com.shqcjd.preinstallglass.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.preinstallglass.model.ResponseData;
import com.shqcjd.preinstallglass.model.pojo.IntentEquipmentBean;
import com.shqcjd.preinstallglass.model.pojo.TaskCodeBean;
import com.shqcjd.preinstallglass.ui.base.BaseActivity;
import com.shqcjd.preinstallglass.ui.base.BasePresenter;
import com.shqcjd.preinstallglass.util.Config;
import com.shqcjd.preinstallglass.util.PrefUtils;
import com.shqcjd.preinstallglass.util.ToastUtils;
import com.shqcjd.preinstallglass.util.UIUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity {
    private static final int REQUEST_CODE_TASK = 10000;//扫描任务号
    private static final int REQUEST_CODE_EQUIPMENT = 10001;//扫描设备
    @BindView(R.id.ll_scan)
    LinearLayout llScan;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.ib_logout)
    Button ib_logout;

    private Context mContext;
    private int userId;
    private int task_id = -1;
    private String userCode;

    @BindView(R.id.mainUpView1)
    MainUpView mMainUpView;
    @BindView(R.id.main_lay)
    FrameMainLayout main_lay11;

    OpenEffectBridge mOpenEffectBridge;
    View mOldFocus;



    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    protected String getVoiceContent() {
        return "|扫码巡检|用户登录|注销;";
    }

    @Override
    protected void onVoiceResult(String result) {
        Logger.i("识别结果:"+result);
        switch (result) {
            case "扫码巡检":
                llScan.performClick();
                break;
            case "用户登录":
                llLogin.performClick();
                break;
            case "注销":
                ib_logout.performClick();
                break;
        }
    }

    @Override
    public void initView() {
        mContext = this;

        PgyCrashManager.register(); //推荐使用
        /** 蒲公英可选配置集成方式 **/
        new PgyUpdateManager.Builder()
                .setForced(false)                //设置是否强制提示更新
                // v3.0.4+ 以上同时可以在官网设置强制更新最高低版本；网站设置和代码设置一种情况成立则提示强制更新
                .setUserCanRetry(false)         //失败后是否提示重新下载
                .setDeleteHistroyApk(true)     // 检查更新前是否删除本地历史 Apk， 默认为true
                .register();


        isShowLogout();

//        Intent intent = new Intent(this, VideotapeService.class);
//        startService(intent);
        mMainUpView.setEffectBridge(new EffectNoDrawBridge());
        mOpenEffectBridge = (OpenEffectBridge) mMainUpView.getEffectBridge();
        Drawable testDrawable = null;
        mMainUpView.setUpRectDrawable(testDrawable); // 设置边框图片
        mMainUpView.setUpRectResource(R.drawable.test_rectangle); // 设置边框图片.

        main_lay11.getViewTreeObserver().addOnGlobalFocusChangeListener(new ViewTreeObserver.OnGlobalFocusChangeListener() {
            @Override
            public void onGlobalFocusChanged(final View oldFocus, final View newFocus) {

                if (newFocus != null)
//                    newFocus.bringToFront(); // 防止放大的view被压在下面. (建议使用MainLayout)
                    mMainUpView.setFocusView(newFocus, mOldFocus, 1.0f);
                mOldFocus = newFocus; // 4.3以下需要自己保存.
                // 测试是否让边框绘制在下面，还是上面. (建议不要使用此函数)
//                if (newFocus != null) {
//                    testTopDemo(newFocus, scale);
//                }
            }
        });
    }


    private void isShowLogout() {
        if (isHasUserInfo()) {
            ib_logout.setVisibility(View.VISIBLE);
        } else {
            ib_logout.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.ll_scan, R.id.ll_login, R.id.ib_logout})
    public void onViewClicked(View view) {
        RxPermissions permissions = new RxPermissions(MainActivity.this);
        switch (view.getId()) {
            case R.id.ll_scan://扫描
                userCode = PrefUtils.getString(mContext, PrefUtils.USER_CODE, "");
                if (true) {
//                if (userCode.isEmpty() || userCode.equals("88888888")) {
                    showDialog();
                    return;
                }


                permissions.setLogging(true);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {
                                if (aBoolean) {
                                    //每次调用相机都需要调用该方法
//                                    UIUtils.handleVideotape(MainActivity.this);
                                    startInspection();
                                } else {
                                    ToastUtils.show(MainActivity.this, "扫描二维码需要打开相机和闪光灯的权限", Toast.LENGTH_SHORT);
                                }
                            }
                        });
                break;
            case R.id.ll_login://登录
                startActivity(new Intent(MainActivity.this, LoginActivity.class));

                break;
            case R.id.ib_logout://注销
                logout();
                break;
        }
    }


    /**
     * 开始巡检
     * 眼镜巡检逻辑:
     * 1.判断本地是否有用户信息
     * 2.有用户信息进入扫描设备逻辑 否则进入扫描任务码逻辑
     * 3.扫描设备 判断进入独立/组设备。并开启全程录像
     * 4.完成巡检后结束全程录像，并返回主页
     */
    private void startInspection() {
        task_id = PrefUtils.getInt(mContext, PrefUtils.TASK_ID, -1);
        if (isHasUserInfo()&&(task_id!=-1)) {
            //扫描设备
            startActivityForResult(new Intent(mContext, QRcodeActivity.class), REQUEST_CODE_EQUIPMENT);
        } else {
            //扫描任务码
            startActivityForResult(new Intent(mContext, QRcodeActivity.class), REQUEST_CODE_TASK);
        }

    }

    /**
     * 判断本地是否有用户信息
     *
     * @return
     */
    private boolean isHasUserInfo() {
        userId = PrefUtils.getInt(this, PrefUtils.USER_ID, -1);
        if (userId != -1) {
            return true;
        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (REQUEST_CODE_TASK == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            //扫描任务码
            handleTask(value);

        } else if (REQUEST_CODE_EQUIPMENT == requestCode && RESULT_OK == resultCode) {
            String value = data.getStringExtra("qr_code_key");
            //扫描设备
            handleEquipment(value);
        }
    }

    private void handleEquipment(String value) {
        if (!UIUtils.isJSONValid(value)){
            qCode(value);
        }else{
            Toast.makeText(mContext, "设备扫描错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void handleTask(String value) {
        //1.判断String是否为json
        if (UIUtils.isJSONValid(value)) {
            //保存用户信息
            TaskCodeBean taskCodeBean = new Gson().fromJson(value, TaskCodeBean.class);
            PrefUtils.setInt(mContext, PrefUtils.USER_ID, taskCodeBean.user_id);
            PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, taskCodeBean.token);
            PrefUtils.setInt(mContext, PrefUtils.TASK_ID, taskCodeBean.task_id);
            task_id = taskCodeBean.task_id;
            isShowLogout();
            ToastUtils.showShort(mContext, "已获取巡检码,请继续扫描设备进行巡检！");
        } else {
            ToastUtils.showShort(mContext, "请扫描正确巡检码！");
        }
    }

    private void logout() {
        PrefUtils.setInt(mContext, PrefUtils.USER_ID, -1);
        PrefUtils.setString(mContext, PrefUtils.USER_CODE, "");
        PrefUtils.setString(mContext, PrefUtils.USER_NAME, "");
        PrefUtils.setString(mContext, PrefUtils.PHONE_NUMBER, "");
        PrefUtils.setString(mContext, PrefUtils.USER_ICON, "");
        PrefUtils.setString(mContext, AppConstant.TOKEN_KEY, "");
        PrefUtils.setInt(mContext, PrefUtils.USER_TYPE, -1);
        PrefUtils.setInt(mContext, PrefUtils.TASK_ID, -1);
        ToastUtils.showShort(mContext, "已注销用户信息!");
        isShowLogout();
    }

    public void qCode(String kksStr){
        task_id = PrefUtils.getInt(mContext, PrefUtils.TASK_ID, -1);
        if(task_id!=-1){
            isInspectionData(kksStr);
        }else{
            //判断是否已登录
            Toast.makeText(mContext, "当前任务不存在", Toast.LENGTH_SHORT).show();
        }
    }

    private void isInspectionData(String kksStr){
        ApiService.intentEquipmentHttp(kksStr.replace("#", "%23"), task_id)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<IntentEquipmentBean>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                        showWaitingDialog("正在加载...");
                    }

                    @Override
                    public void _onNext(ResponseData<IntentEquipmentBean> responseData) {
                        hideWaitingDialog();
                        if(responseData.retCode==10000){
                            if(responseData.data.check_gps){
                                showWaitingDialog("获取地理位置");
                                RxPermissions permissions = new RxPermissions(MainActivity.this);
                                permissions.setLogging(true);
                                permissions.request(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
                                        .subscribe(new Consumer<Boolean>() {
                                            @Override
                                            public void accept(Boolean aBoolean) throws Exception {
                                                if (aBoolean) {
                                                    MyApp.startLocation();
                                                    MyApp.setOnLocationCallBack(new MyApp.OnLocationInterface() {
                                                        @Override
                                                        public void onLocationInterface(AMapLocation aMapLocation) {
                                                            hideWaitingDialog();
                                                            LatLng desLatLng = UIUtils.getGpsChangeLocation(responseData.data.latitude, responseData.data.longitude, mContext);
                                                            //当前坐标
                                                            double cLongitude = aMapLocation.getLongitude();
                                                            double cLatitude = aMapLocation.getLatitude();
                                                            float distance = AMapUtils.calculateLineDistance(desLatLng, new LatLng(cLatitude, cLongitude));
                                                            if(distance<Config.INSPECTION_DISTANCE){
                                                                if(responseData.data.isgroup){
                                                                    Intent it = new Intent(mContext, InspectionStandardActivity.class);
                                                                    it.putExtra("kks", kksStr);
                                                                    it.putExtra("tId", task_id);
                                                                    startActivity(it);
                                                                }else{
                                                                    Intent it = new Intent(mContext, NewEquipmentInspectionActivity.class);
                                                                    it.putExtra("tId", task_id);
                                                                    it.putExtra("kks", kksStr);
                                                                    startActivity(it);
                                                                }
                                                            }else{
                                                                Toast.makeText(mContext, "当前位置距离巡检点超过了"+Config.INSPECTION_DISTANCE+"米，请靠近一点再试试", Toast.LENGTH_SHORT).show();
                                                            }
                                                        }
                                                    });
                                                } else {
                                                    ToastUtils.show(mContext, "巡检需要获取定位的权限", Toast.LENGTH_SHORT);
                                                }
                                            }
                                        });

                            }else{
                                hideWaitingDialog();
                                if(responseData.data.isgroup){
                                    Intent it = new Intent(mContext, InspectionStandardActivity.class);
                                    it.putExtra("kks", kksStr);
                                    it.putExtra("tId", task_id);
                                    startActivity(it);
                                }else{
                                    Intent it = new Intent(mContext, NewEquipmentInspectionActivity.class);
                                    it.putExtra("tId", task_id);
                                    it.putExtra("kks", kksStr);
                                    startActivity(it);
                                }
                            }


                        }else{
                            hideWaitingDialog();
                            Toast.makeText(mContext, responseData.retMsg, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                        Toast.makeText(mContext, "任务不存在", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void showDialog() {
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_del_view, false)
                .show();
        Window window = dialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = 630;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        dialog.onWindowAttributesChanged(lp);
        window.setAttributes(lp);

        View customeView = dialog.getCustomView();

        TextView tv_title = customeView.findViewById(R.id.tv_title);
        Button follow = (Button) customeView.findViewById(R.id.btn_follow);
        Button cancel = customeView.findViewById(R.id.btn_cancel);

        tv_title.setText("开放功能请联系我们\n联系电话:021-62596228");
        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        Intent intent = new Intent(this, VideotapeService.class);
//        stopService(intent);

    }
}
